#!/usr/bin/env python3

import sys

from dali.driver import hasseb
#from dali.driver.hasseb import Bus
# from dali import bus
from dali import address
import dali.gear.general as gear

# Create hasseb USB DALI driver instance to handle messages
DALI_device = hasseb.SyncHassebDALIUSBDriver()
# Create DALI bus
DALI_bus = hasseb.Bus('hasseb DALI bus',   DALI_device)

# Print help if no arguments
if len(sys.argv) == 1:
    print("Hasseb Dali master test program.")
    print(f"Usage: python {sys.argv[0]} command [shortaddress]")
    print(f"e.g. : python {sys.argv[0]} initialize")
    print(f"e.g. : python {sys.argv[0]} scan")
    print(f"e.g. : python {sys.argv[0]} Off 0")
    print(f"e.g. : python {sys.argv[0]} RecallMaxLevel 0")
    exit(-1)

if sys.argv[1] == 'initialize':
    print("Initializing bus...")
    DALI_bus.initialize_bus()
    print("Address \t| Random address \t| Groups \t| Device type")
    for i in range(len(DALI_bus._devices)):
        print(f"{DALI_bus._devices[i].address} \t\t| {DALI_bus._devices[i].randomAddress} \t\t| {DALI_bus._devices[i].groups} \t\t| {DALI_bus._devices[i].deviceType}")
# Scan bus
elif sys.argv[1] == 'scan':
    print("Scanning bus...")
    DALI_bus.assign_short_addresses()
    print("Address \t| Groups \t| Device type")
    for i in range(len(DALI_bus._devices)):
        print(f"{DALI_bus._devices[i].address} \t\t| {DALI_bus._devices[i].groups} \t\t| {DALI_bus._devices[i].deviceType}")
else:
    if len(sys.argv) == 2:
        adr = 0
    else:
        adr = address.Short(int(sys.argv[2]))
    str = "print(DALI_device.send(gear." + sys.argv[1] + "(adr)))"
    #print(DALI_device.send(gear.QueryActualLevel(adr)))
    eval(str)